﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using CMN.Config;
using System.Reflection;
using CMN.Common;
//http://www.cnblogs.com/hjf1223/archive/2010/10/08/background-tasks.html
namespace CMN.Extends.Job
{
    public class Jobs
    {

        private static readonly Jobs instance = new Jobs();

        private Dictionary<string, JobExecutor> jobs = new Dictionary<string, JobExecutor>();

        public void LoadJobs()
        {
            List<AutoJobInfo> configs = AutoJobConfigs.GetAutoJobConfig().AutoJobInfos;
            foreach (AutoJobInfo info in configs)
            {
                if (info.IsWork)
                {
                    try
                    {
                        var t = Type.GetType(info.NameSpace);
                        ConstructorInfo ct1 = t.GetConstructor(System.Type.EmptyTypes);
                        if (ct1 != null)
                        {
                            IJob job = (IJob)ct1.Invoke(null);
                            if (info.Interval < 500)
                                info.Interval = 600;
                            Instance.AttachJob(info.NameSpace, job, info.Interval, null, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        AppLog.Write("初始计划任务类错误" + info.NameSpace, AppLog.LogMessageType.Error, ex);
                    }
                }
            }
        }

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static Jobs Instance
        {
            get { return instance; }
        }

        public void AttachJob(string name, IJob job, int interval, object executionState, bool start)
        {
            lock (lockHelper)
            {
                var jobExecutor = new JobExecutor(job, interval, executionState);
                jobs[name] = jobExecutor;
                jobExecutor.Start();
                
            }
        }

        static object lockHelper = new object();
        public void Start()
        {
            lock (lockHelper)
            {
                foreach (var job in jobs.Values)
                {
                    AppLog.Write(string.Concat("任务：", job.ToString(), "-Start"), AppLog.LogMessageType.Debug);
                    job.Start();
                }
            }
        }
        /// <summary>
        /// Stops this instance.
        /// </summary>
        public void Stop()
        {
            lock (jobs)
            {
                foreach (JobExecutor job in jobs.Values)
                {
                    AppLog.Write(string.Concat("任务：", job.ToString(), "-Stop"), AppLog.LogMessageType.Debug);
                    job.Stop();
                }
            }
        }
    }
}